package com.example.wac.interceptor;

import com.example.wac.annotation.UnJwtToken;
import com.example.wac.enums.ErrorCode;
import com.example.wac.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author wuancheng
 * @description
 * @date 2021-07-13 10:52:00
 */

@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    private static Logger log = LoggerFactory.getLogger(HandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //controller不携带UnJwtToken注解就校验，携带放行
            UnJwtToken annotation = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), UnJwtToken.class);
            if(null == annotation){
                String token = request.getHeader("token");
                Optional.ofNullable(token).orElseThrow(ErrorCode.TOKEN_ERROR::getAppException);
                return JwtUtil.checkSign(request,token);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}